package com.seveneight.baijiesteward.ui.first.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseFragmentBack;
import com.seveneight.baijiesteward.bean.CardBean;
import com.seveneight.baijiesteward.bean.CreditBean;
import com.seveneight.baijiesteward.bean.OrderBean;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.http.HttpConfig;
import com.seveneight.baijiesteward.ui.first.contract.CreatCashOrderContract;
import com.seveneight.baijiesteward.ui.first.presenter.CreatCashOrderPresenter;
import com.seveneight.baijiesteward.ui.main.activity.WebActivity;
import com.seveneight.baijiesteward.ui.user.activity.CreditCardListActivity;
import com.seveneight.baijiesteward.ui.user.activity.ManagerCardActivity;
import com.seveneight.baijiesteward.ui.user.activity.RecordActivity;
import com.seveneight.baijiesteward.utils.ArithmeticUtils;
import com.seveneight.baijiesteward.utils.GlideLoader;
import com.seveneight.baijiesteward.utils.NumberUtil;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.utils.WindowUtil;

import java.math.BigDecimal;

/**
 * Created by user1 on 2018/2/13.
 */

public class CashierFragment extends BaseFragmentBack implements View.OnClickListener, CreatCashOrderContract.CreateCashOderView {

    CreatCashOrderContract.CreateCashOderPresenter createCashOderPresenter;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_record;
    private TextView tv_rate;
    private TextView et_input;
    private UserBean bean;
    private TextView tv_finallyMoney;
    private ImageView iv_creditlogo;
    private TextView tv_creditbank;
    private TextView tv_creditNo;
    private ImageView iv_debitlogo;
    private TextView tv_debitbank;
    private TextView tv_debitNo;
    private TextView tv_next;
    private CreditBean creditBean;
    private CardBean cardBean;
    private double release2;
    private String inputMoney;
    private LinearLayout layout_gocredit;
    private LinearLayout layout_godebit;

    @Override
    protected int getContentView() {
        return R.layout.fragment_cashier;
    }

    public static CashierFragment newInstance() {
        Bundle args = new Bundle();
        CashierFragment fragment = new CashierFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        tv_finallyMoney = findView(R.id.tv_finallyMoney);
        et_input = findView(R.id.et_input);
        iv_back = findView(R.id.iv_back);
        tv_title = findView(R.id.tv_title);
        tv_title.setText("收银台");
        tv_record = findView(R.id.tv_record);
        tv_rate = findView(R.id.tv_rate);
        iv_creditlogo = findView(R.id.iv_creditlogo);
        tv_creditbank = findView(R.id.tv_creditbank);
        layout_gocredit = findView(R.id.layout_gocredit);
        tv_creditNo = findView(R.id.tv_creditNo);
        tv_debitNo = findView(R.id.tv_debitNo);
        iv_debitlogo = findView(R.id.iv_debitlogo);
        tv_debitbank = findView(R.id.tv_debitbank);
        layout_godebit = findView(R.id.layout_godebit);
        tv_next = findView(R.id.tv_next);
    }

    @Override
    protected void initData() {
        bean = setting.getUserInfo();
        tv_rate.setText("费率:" + NumberUtil.getPercentFormat(bean.getWRate()) + " " + "单笔手续费" + bean.getWBrokerage() + "元");
        createCashOderPresenter = new CreatCashOrderPresenter(this);
    }

    @Override
    protected void setListener() {
        layout_gocredit.setOnClickListener(this);
        layout_godebit.setOnClickListener(this);
        tv_next.setOnClickListener(this);
        tv_record.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        et_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                countMoney();
            }
        });
    }

    private void countMoney() {
        inputMoney = et_input.getText().toString();
        if (inputMoney.length() < 1) {
            return;
        }
        double money = Double.parseDouble(inputMoney);
        double minMoney = 10.00;
        BigDecimal data1 = new BigDecimal(inputMoney);
        BigDecimal data2 = new BigDecimal(minMoney);
        if (data1.compareTo(data2) == -1) {
            return;
        }
        double release = ArithmeticUtils.mul(Double.parseDouble(bean.getWRate()), money);
        release2 = ArithmeticUtils.sub(ArithmeticUtils.sub(money, release), Double.parseDouble(bean.getWBrokerage()));
        tv_finallyMoney.setText(release2 + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                _mActivity.onBackPressed();
                break;
            case R.id.tv_record:
                Bundle bundle1 = new Bundle();
                bundle1.putString("type", "6");
                WindowUtil.getInstance().startActivity(mContext, RecordActivity.class, bundle1);
                break;
            case R.id.tv_next:
                goTrans();
                break;
            case R.id.layout_godebit:
                Bundle bundle = new Bundle();
                bundle.putInt("type", 2);
                Intent intent = new Intent(mContext, ManagerCardActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, AppConfig.REQUEST_CODE_1);
                break;
            case R.id.layout_gocredit:
                Intent i = new Intent(mContext, CreditCardListActivity.class);
                startActivityForResult(i, AppConfig.REQUEST_CODE_0);
                break;
        }
    }

    private void goTrans() {
        String amount = et_input.getText().toString();
        if (TextUtils.isEmpty(amount)) {
            showDialog("请输入金额");
            return;
        }
        if (creditBean == null) {
            showDialog("请选择信用卡");
            return;
        }
        if (cardBean == null) {
            showDialog("请选择结算卡");
            return;
        }
        showInputDialogCustomInvalidation();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }

        if (requestCode == AppConfig.REQUEST_CODE_0 && resultCode == RESULT_OK) {//信用卡
            creditBean = (CreditBean) data.getSerializableExtra("bean");
            initCreditCrd();
        }
        if (requestCode == AppConfig.REQUEST_CODE_1 && resultCode == RESULT_OK) {//借记卡
            cardBean = (CardBean) data.getSerializableExtra("bean");
            initDebitCard();
        }
    }

    private void initCreditCrd() {
        GlideLoader.displayImg(mContext, HttpConfig.SOURCE_URL + creditBean.getIcoUrl(), iv_creditlogo);
        tv_creditbank.setText(creditBean.getBankName());
        tv_creditNo.setText("尾号" + creditBean.getCreditCardNo().substring(creditBean.getCreditCardNo().length() - 4) + " 信用卡");
    }

    private void initDebitCard() {
        GlideLoader.displayImg(mContext, HttpConfig.SOURCE_URL + cardBean.getIcoUrl(), iv_debitlogo);
        tv_debitbank.setText(cardBean.getBankName());
        tv_debitNo.setText("尾号" + cardBean.getBankCardNo().substring(cardBean.getBankCardNo().length() - 4) + " 借记卡");
    }

    @Override
    public void reBackOrderInfo(OrderBean orderBean) {
        if (orderBean.getOrderStatus() == 101 && !TextUtils.isEmpty(orderBean.getPayInfo())) {
            Bundle bundle = new Bundle();
            bundle.putString("url", orderBean.getPayInfo());
            WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle);
        } else {
            if (!TextUtils.isEmpty(orderBean.getDescription())){
                showDialog(orderBean.getDescription());
            }else{
                showDialog("交易失败，请重新尝试");
            }
        }
    }

    public void showInputDialogCustomInvalidation() {
        new MaterialDialog.Builder(mContext)
                .title("温馨提示")
                .backgroundColorRes(R.color.white)
                .titleColorRes(R.color.mainblue)
                .positiveColorRes(R.color.mainblue)
                .contentColorRes(R.color.graytext)
                .widgetColorRes(R.color.mainblue)
                .content("请输入交易密码")
                .inputType(
                        InputType.TYPE_TEXT_VARIATION_PASSWORD)
                .positiveText("确定")
                .input(
                        "",
                        "", false,
                        (dialog, input) -> stratToPay(input.toString()))
                .show();
    }

    private void stratToPay(String password) {
        createCashOderPresenter.createOrder(mContext, jsonFormat.createOrder(
                inputMoney,
                "0",
                cardBean.getDebitCardID(),
                "1",
                creditBean.getCreditCardID(), password, 6));
    }
}
